<template>
	<view>


		<block v-if="user.role === 'User'">
			<form @submit="formSubmit" @reset="formReset">
			<view style="display:none" class="uni-form-item uni-column" v-if="categorys.length">
				<view class="title">类别</view>
				<picker @change="bindPickerChange" :value="index" :range="categorys" range-key="title">
					<view class="uni-input">{{categorys[index].title}}</view>
				</picker>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">标题
					<text v-if="error_messages.title" class="text-red">{{ error_messages.title }}</text>
				</view>
				<input v-model="form.title" class="uni-input" placeholder="输入标题" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">正文
					<text v-if="error_messages.content" class="text-red">{{ error_messages.content }}</text>
				</view>
				<view class="uni-textarea" style="width:96%;padding:6px 2%;">
					<textarea v-model="form.content" auto-height placeholder="输入正文内容，自动多行。" />
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">上传图片(最多允许9张)</view>
				<view class="uni-uploader__files" style="padding:6px 2%;background: #FFF;">
					<block v-for="(image,index) in imageList" :key="index">
						<view class="uni-uploader__file">
							<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
							<view :data-index="index" :data-src="image" @click="delete_img">删除</view>
						</view>
					</block>
					<view class="uni-uploader__input-box">
						<view class="uni-uploader__input" @tap="chooseImage"></view>
					</view>
				</view>
			</view>
			<view class="uni-btn-v" style="padding:9px 3%;">
				<button type="primary" formType="submit">报送</button>
				<button type="default" formType="reset">重置</button>
			</view>
			</form>
		</block>

		<block class="uni-flex uni-column list" v-if="user.role === 'Administrator' || user.role === 'Leadership' || user.role === 'Audit'">
			<view class="my-header">
				<view class="item-title">
					<view class="font-18">总期数</view>
					<view style="font-size: 24px;">{{ meta.total_count }}</view>
				</view>

				<view class="body">
					<view class="my-item" style="border-right: 1px solid #737373;">
						<view class="font-16">报送</view>
						<view class="font-16">{{ meta.hired_count + meta.not_hired_count }}</view>
					</view>
					<view class="my-item" style="border-right: 1px solid #737373;">
						<view class="font-16">录用</view>
						<view class="font-16">{{ meta.hired_count }}</view>
					</view>
					<view class="my-item">
						<view class="font-16">未录用</view>
						<view class="font-16">{{ meta.not_hired_count }}</view>
					</view>
				</view>

			</view>

			<view class="uni-flex list-cell" v-for="(item, index) in reports" :key="index">
				<navigator :url="'../reports/view?id='+item.id" hover-class="navigator-hover">
				<view class="uni-column list-cell-body">
					<view class="body-title">
						<view style="font-size:16px;">{{ item.title }}</view>
					</view>
					<view class="uni-flex body-footer">
						<view>第 {{ item.sub_title }} 期</view>
					</view>
				</view>
				</navigator>
			</view>
			<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>

		</block>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import * as API from 'server/getData'
	import * as types from 'store/mutations_types'


	export default {
		data () {
			return {
				index: 0,
				imageList: [],
				categorys: [],
				form: {
					cid: '',
					title: '',
					content: '',
					attachment: []
				},
				count: 9,
				showLoadMore: false,
				page: 0,
				reports: [],
				meta: [],
				loadMoreText: "加载中...",
				error_messages: [],
				showLoadMore: false
			}
		},
		onLoad() {
			this.initData()
		},
		onBackPress(event) {
			uni.switchTab({
				url: '../users/index'
			});
			return true
		},
		onPullDownRefresh () {
			this.initData()
		},
		onReachBottom() {
			this.showLoadMore = true;
			this.initData(false)
		},
		computed: {
			...mapState(['user', 'token'])
		},
		methods: {
			async initData(pull=true) {
				this.getCategorys()
				this.page = !pull ? this.page + 1 : 1
				let res = await API.articles.fetchReports({page: this.page})
				console.log(res)
				if (res.success === true) {
					if (res.data.items.length === 0) {
						this.loadMoreText = '已经没有了'
					}
					this.reports = pull ? res.data.items : this.reports.concat(res.data.items)
					this.meta = res.data._meta
				}
				uni.stopPullDownRefresh()

				// API.articles.fetchReports({page: this.page}).then(r => {
				// 	if (r.success === true) {
				// 		if (r.data.items.length === 0) {
				// 			this.loadMoreText = '已经没有了'
				// 		}
				// 		this.reports = pull ? r.data.items : this.reports.concat(r.data.items)
				// 	}
				// 	uni.stopPullDownRefresh()
				// })
			},
			// 获取分类栏目
			async getCategorys() {
				let res = await API.articles.fetchCategorys()
				if (res.success) {
					this.categorys = res.data.items
					this.form.cid = this.categorys[0].id
				}
			},
			bindPickerChange: function(e) {
				this.index = e.target.value
				this.form.cid = this.categorys[this.index]['id']
			},
			// 选择图片
			chooseImage: async function() {
				uni.chooseImage({
					count: this.count,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						if (res.tempFilePaths.length > this.count) {
							uni.showModal({content: `多于${this.count}张`})
							return false
						}
						// this.imageList = this.imageList.concat(res.tempFilePaths);
						let imagePathArr = res.tempFilePaths
						for (let item of imagePathArr) {
							uni.uploadFile({
								url: 'https://report.lswkdb.com/api/articles/attachment',
								filePath: item,
								fileType: 'image',
								header: {'Authorization': `Bearer ${this.token['access_token']}`},
								name: 'upload',
								success: (res) => {
									let res_data = JSON.parse(res.data)
									if (res_data.success === false) {
										uni.showModal({ title: '上传失败', content: res_data.message[0], showCancel:false })
										return false
									}
									uni.showToast({ title: '上传成功', icon: 'success', duration: 1000 })
									this.form.attachment.push(res_data.id)
									this.imageList.push(res_data.url)
								},
								fail: (err) => {
									uni.showModal({
										content: '错了',
										showCancel: false
									});
								}
							})
						}
					}
				})
			},
			delete_img: async function (e) {
				this.imageList.splice(e.target.dataset['index'], 1)
				let id = e.target.dataset['src'].split('#')[1]
				if (id) {
					let res = await API.articles.del_attachment({'id': id})
					this.form.attachment.pop(id)
				}
			},
			formSubmit: async function() {
				this.form.attachment = JSON.stringify(this.form.attachment)
				let res = await API.articles.addArticle(this.form)

				if (!res.success) {
					this.error_messages = res.message[0]
					return false
				}

				if (res.success) {
					let _this = this
					uni.showToast({title: '添加成功', duration: 2000})
					setTimeout(function () {
						_this.imageList = []
						_this.form = { 
							cid: '',
							title: '',
							content: '',
							attachment: []
						}
						_this.$store.commit(types.UPDATE_REFRESH, {'is_refresh': true})
						uni.switchTab({
							url: '/pages/articles/index?id=2'
						})
					}, 2000)
				}
			},
			// 预览图片
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			formReset: function(e) {
				this.imageList = []
				this.form = { 
					cid: '',
					title: '',
					content: '',
					attachment: []
				}
			}
		}
	}
</script>

<style>
page { height: auto; min-height: 100%; }
.my-header {
	background: #484b84;
	display: flex;
	padding: 10px 10px;
	flex-direction: column;
}
.uni-uploader__file {
	display: flex;
    flex-direction: column;
    align-items: center;
	height: 140px;
}
.item-title {
	display: flex;
	flex-direction: column;
	align-items: center;
}
.item-title uni-view, .item-title view {
    font-size: 18px;
	font-weight: bold;
	color: #fbe5e5;
}
.font-18 {
	font-size: 18px;
}
.font-16 {
	font-size: 16px;
}
.body {
	display: flex;
	flex-direction: row;
	margin-top: 10px;
}
.my-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: auto;
    font-size: 16px;
	font-weight: bold;
	color: #fbe5e5;
}
.list {}
.list-cell{padding:11px 15px;background:#fff;border-bottom:1px solid #eee;}
.list-cell .list-cell-image image{width:150upx; height:120upx}
.list-cell .list-cell-body{flex:1;justify-content:space-around;}
.body-title{line-height: 18px;height:37px;}
.body-footer{color: #8f8f94;justify-content: space-between;}
	.text-red {
		color: red;
		margin-left: 10px;
	}
</style>
